package com.czc.weather.push.weather.service;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import com.czc.weather.push.weather.entity.PushData;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

@Service
public class PushDataService {

    private final ObjectMapper objectMapper = new ObjectMapper();
    private final String JSON_FILE = "pushData.json";

    @Autowired
    private WeathernfoService weathernfoService;


    public List<PushData> getPushData() throws IOException {
        File dataFile = getDataFile();
        List<PushData> dataList = readDataFromFile(dataFile);
        return dataList;
    }

    public ResponseEntity<String> savePushInfo(PushData pushData) throws Exception {
        try {
            // 获取文件路径（存放在项目根目录）
            File dataFile = getDataFile();
            
            // 读取现有数据
            List<PushData> dataList = readDataFromFile(dataFile);
            
            // 检查并处理mobile
            boolean existed = dataList.removeIf(item -> item.getMobile().equals(pushData.getMobile()));

            //处理地区代码
            String areaCode= weathernfoService.getAreaCode(pushData.getAreaCode());
            if(areaCode==null){
                throw new Exception("未查询到对应地区，请检查输入");
            }
            pushData.setAreaCode(areaCode);
        
            // 添加新数据
            dataList.add(pushData);
            
            // 写回文件
            writeDataToFile(dataFile, dataList);
            
            String message = existed ? "绑定手机号已存在，已完成替换" : "绑定手机号不存在，已新增数据";
            return ResponseEntity.ok(message);
        } catch (IOException e) {
            return ResponseEntity.internalServerError()
                .body("数据处理失败: " + e.getMessage());
        }
    }

    // 删除指定手机号的数据
    public void removePushDataByMobile(String mobile) throws IOException {
        File dataFile = getDataFile();
        List<PushData> dataList = readDataFromFile(dataFile);
        
        // 移除指定手机号的数据
        boolean removed = dataList.removeIf(item -> item.getMobile().equals(mobile));
        
        if (removed) {
            // 写回文件
            writeDataToFile(dataFile, dataList);
        }
    }

    private List<PushData> readDataFromFile(File file) throws IOException {
        if (file.length() == 0) {
            return new ArrayList<>();
        }
        return objectMapper.readValue(file, new TypeReference<List<PushData>>() {
        });
    }

    private void writeDataToFile(File file, List<PushData> data) throws IOException {
        objectMapper.writerWithDefaultPrettyPrinter().writeValue(file, data);
    }

    private File getDataFile() throws IOException {
        File file = new File(JSON_FILE);
        if (!file.exists()) {
            file.createNewFile();
            objectMapper.writeValue(file, new ArrayList<>());
        }
        return file;
    }
}